﻿using AutoMapper;
using Domain.User;
using Infratructure;
using Infratructure.Interface;
using MediatR;
using MES.Server.API.Application.Command.Account.DocumentCodeRuleCommand;
using MES.Server.API.Dto.Account;
using MES.Server.API.Helpers;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using ReturnValue;

namespace MES.Server.API.Application.Handler.Account.DocumentCodeRuleCommandHandler
{

    public class CreateDocumentCodeRuleHandler : IRequestHandler<CreateDocumentCodeRuleCommand, ApiResult<DocumentCodeRule>>
    {
        private readonly IRepository<DocumentCodeRule> _ruleRepo;

        public CreateDocumentCodeRuleHandler(IRepository<DocumentCodeRule> ruleRepo)
        {
            _ruleRepo = ruleRepo;
        }

        public async Task<ApiResult<DocumentCodeRule>> Handle(CreateDocumentCodeRuleCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<DocumentCodeRule>();

            try
            {
                // 1. 验证业务实体唯一性
                var exists = await _ruleRepo.GetAll()
                    .AnyAsync(r => r.BusinessEntity == request.BusinessEntity);
                if (exists)
                    return result.Fail("该业务实体已存在编码规则");

                // 2. 创建规则
                var rule = new DocumentCodeRule
                {
                    BusinessEntity = request.BusinessEntity,
                    RuleName = request.RuleName,
                    EntityField = request.EntityField,
                    DateField = request.DateField,
                    Prefix = request.Prefix,
                    RuleType = request.RuleType,
                    NumberDigits = request.NumberDigits,
                    GrowthType = request.GrowthType,
                    Connector = request.Connector,
                    // 为CreaterPeople字段赋值，这里假设从某个地方获取当前用户，比如UserContext.CurrentUser
                    CreaterPeople = "admin" // 替换为实际获取创建人的方式
                };

                // 3. 生成预览编码
                rule.CodePreview = DocumentCodeHelper.PreviewCode(rule);

                // 4. 保存规则
                var dbResult = await _ruleRepo.AddAsync(rule);

                // 修复：返回创建的规则对象
                if (dbResult > 0)
                {
                    // 重新从数据库获取完整的规则数据（包含ID等）
                    var savedRule = await _ruleRepo.GetAll()
                        .FirstOrDefaultAsync(r => r.BusinessEntity == request.BusinessEntity);

                    return result.Success("编码规则创建成功", savedRule);
                }
                else
                {
                    return result.Fail("编码规则创建失败");
                }
            }
            catch (Exception ex)
            {
                // 添加异常处理
                return result.Fail($"创建编码规则时发生错误: {ex.Message}");
            }
        }
    }

    public class GetDocumentCodeRulesHandler : IRequestHandler<GetDocumentCodeRulesCommand, ApiPaging<DocumentCodeRule>>
    {
        private readonly IRepository<DocumentCodeRule> _ruleRepo;

        public GetDocumentCodeRulesHandler(IRepository<DocumentCodeRule> ruleRepo)
        {
            _ruleRepo = ruleRepo;
        }

        public async Task<ApiPaging<DocumentCodeRule>> Handle(GetDocumentCodeRulesCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<DocumentCodeRule>
            {
                Code = StatusCode.Success,
                Message = "查询成功"
            };

            var query = _ruleRepo.GetAll().AsQueryable();

            if (!string.IsNullOrEmpty(request.BusinessEntity))
                query = query.Where(r => r.BusinessEntity.Contains(request.BusinessEntity));

            if (!string.IsNullOrEmpty(request.RuleName))
                query = query.Where(r => r.RuleName.Contains(request.RuleName));

            result.Totalcount = await query.CountAsync(cancellationToken);

            var rules = await query
                .OrderBy(r => r.BusinessEntity)
                .Skip((request.PageIndex - 1) * request.PageSize)
                .Take(request.PageSize)
                .ToListAsync(cancellationToken);

            // 为每个规则生成预览编码
            foreach (var rule in rules)
            {
                rule.CodePreview = DocumentCodeHelper.PreviewCode(rule);
            }

            result.TotalPage = rules;
            return result;
        }
    }

    public class UpdateDocumentCodeRuleHandler : IRequestHandler<UpdateDocumentCodeRuleCommand, ApiResult<DocumentCodeRule>>
    {
        private readonly IRepository<DocumentCodeRule> _ruleRepo;

        public UpdateDocumentCodeRuleHandler(IRepository<DocumentCodeRule> ruleRepo)
        {
            _ruleRepo = ruleRepo;
        }

        public async Task<ApiResult<DocumentCodeRule>> Handle(UpdateDocumentCodeRuleCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<DocumentCodeRule>();

            // 1. 获取要更新的规则
            var rule = await _ruleRepo.GetValue(request.Id);
            if (rule == null)
                return result.Fail("编码规则不存在");

            // 2. 验证业务实体唯一性（排除自身）
            var exists = await _ruleRepo.GetAll()
                .AnyAsync(r => r.BusinessEntity == request.BusinessEntity && r.Id != request.Id);
            if (exists)
                return result.Fail("该业务实体已存在编码规则");

            // 3. 更新规则
            rule.BusinessEntity = request.BusinessEntity;
            rule.RuleName = request.RuleName;
            rule.EntityField = request.EntityField;
            rule.DateField = request.DateField;
            rule.Prefix = request.Prefix;
            rule.RuleType = request.RuleType;
            rule.NumberDigits = request.NumberDigits;
            rule.GrowthType = request.GrowthType;
            rule.Connector = request.Connector;

            // 4. 生成预览编码
            rule.CodePreview = DocumentCodeHelper.PreviewCode(rule);

            // 5. 保存更新
            var dbResult = await _ruleRepo.UpdateAsync(rule);
            return dbResult > 0
                ? result.Success("编码规则更新成功", rule)
                : result.Fail("编码规则更新失败");
        }
    }

    public class DeleteDocumentCodeRuleHandler : IRequestHandler<DeleteDocumentCodeRuleCommand, ApiResult<object>>
    {
        private readonly IRepository<DocumentCodeRule> _ruleRepo;
        private readonly DateContext _dbContext;

        public DeleteDocumentCodeRuleHandler(
            IRepository<DocumentCodeRule> ruleRepo,
            DateContext dbContext)
        {
            _ruleRepo = ruleRepo;
            _dbContext = dbContext;
        }

        public async Task<ApiResult<object>> Handle(DeleteDocumentCodeRuleCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiResult<object>();

            // 1. 获取要删除的规则
            var rule = await _ruleRepo.GetValue(request.Id);
            if (rule == null)
                return result.Fail("编码规则不存在");

            // 2. 执行删除
            _dbContext.Set<DocumentCodeRule>().Remove(rule);
            var dbResult = await _dbContext.SaveChangesAsync(cancellationToken);

            return dbResult > 0
                ? result.Success("编码规则删除成功", null)
                : result.Fail("编码规则删除失败");
        }
    }
}
